package com.gitee.ywj14352.action.echo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 初始化一个 Echo sever 最简单的
 * 直接接受单个信息
 * @author yangwenjie.a
 */
public class EchoServer {
    public static final Logger LOGGER = LoggerFactory.getLogger(EchoServer.class);
    private final int port;
    private final String host;
    private final EchoServerHandler serverHandler;


    public EchoServer(String host, int port) {
        this.host = host;
        this.port = port;
        this.serverHandler = new EchoServerHandler();
    }

    public void start() {
        // 父组
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        // 工作线程组
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            serverBootstrap.group(bossGroup, workerGroup);

            serverBootstrap.channel(NioServerSocketChannel.class);

            serverBootstrap.localAddress(host, port);
            //绑定 childHandler
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(serverHandler);

                }
            });

            // 等待 直到完成绑定
            ChannelFuture future = serverBootstrap.bind().sync();

            future.channel().closeFuture().sync();

        } catch (Exception e) {
            LOGGER.error("start Echo has error ", e);
        }

    }


    public static void main(String[] args) {

        EchoServer echoServer = new EchoServer("127.0.0.1", 8990);

        echoServer.start();
    }

}
